import axios, {AxiosRequestConfig} from 'axios';
import {message} from 'antd';
// import { toLogin } from '@/utils/login';
export const baseURL: string = "https://cdn.jsdelivr.net/gh/IceRain-mvc/interview@1.9.4/";
// export const baseURL: string = "/";
// export const baseURL: string = "http://110.40.133.139:4000";
export const httpProvider = axios.create({
  baseURL,
  timeout: 60000,
});

httpProvider.interceptors.request.use(
  (config) => {
    if (typeof window !== 'undefined') {
      const token = window.localStorage.getItem('token');
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    return config;
  },
  () => {
    throw new Error('发起请求出错');
  }
);

httpProvider.interceptors.response.use(
  (res) => {
    // if (res.status && res.status === 200 && res.data.status === 'error') {
    //   typeof window !== 'undefined' && message.error({message: res.data.msg});
    //   return null;
    // }
    // const result = res.data;
    // if (!result.success) {
    //   message.error(result.msg);
    //   return null;
    // }
    return res.data;
  },
  (err) => {
    if (err && err.response && err.response.status) {
      const status = err.response.status;
      const isClient = typeof window !== 'undefined';

      switch (status) {
        // 服务器的错误
        case 500:
        case 504:
        case 404:
          isClient && message.error('服务器异常');
          break;
        // 客户端的错误
        case 403:
          isClient && message.warn('访客无权进行该操作');
          break;
        // 未授权 : token 出错了 token过期了
        case 401:
          isClient && message.info('请重新登录');
          // toLogin();
          break;

        default:
          isClient &&
          message.error(
            (err.response && err.response.data && err.response.data.msg) || '未知错误!'
          );
      }
    }

    return Promise.reject(err);
  }
);
